const UserService = require('../service/UserService');

class UserController {
    static async createUser(ctx) {
        try {
            const userData = ctx.request.body;
            const user = await UserService.createUser(userData);
            ctx.status = 201;
            ctx.body = user;
        } catch (error) {
            ctx.status = 400;
            ctx.body = { error: error.message };
        }
    }

    static async getUsers(ctx) {
        try {
            const users = await UserService.getUsers();
            ctx.status = 200;
            ctx.body = users;
        } catch (error) {
            ctx.status = 500;
            ctx.body = { error: error.message };
        }
    }

    static async getUserById(ctx) {
        try {
            const userId = ctx.params.id;
            const user = await UserService.getUserById(userId);
            if (!user) {
                ctx.status = 404;
                ctx.body = { error: 'User not found' };
            } else {
                ctx.status = 200;
                ctx.body = user;
            }
        } catch (error) {
            ctx.status = 500;
            ctx.body = { error: error.message };
        }
    }

    static async updateUser(ctx) {
        try {
            const userId = ctx.params.id;
            const updateData = ctx.request.body;
            const user = await UserService.updateUser(userId, updateData);
            if (!user) {
                ctx.status = 404;
                ctx.body = { error: 'User not found' };
            } else {
                ctx.status = 200;
                ctx.body = user;
            }
        } catch (error) {
            ctx.status = 400;
            ctx.body = { error: error.message };
        }
    }

    static async deleteUser(ctx) {
        try {
            const userId = ctx.params.id;
            const user = await UserService.deleteUser(userId);
            if (!user) {
                ctx.status = 404;
                ctx.body = { error: 'User not found' };
            } else {
                ctx.status = 200;
                ctx.body = { message: 'User deleted successfully' };
            }
        } catch (error) {
            ctx.status = 500;
            ctx.body = { error: error.message };
        }
    }
}

module.exports = UserController;